#!/bin/bash
# shellcheck source=meta-facebook/meta-yosemite4/recipes-yosemite4/plat-tool/files/yosemite4-common-functions
source /usr/libexec/yosemite4-common-functions
echo "Start rescan-fru-oct-setting"
# We observed that the rescan service would be execute during BMC
# boot up, and the entity-manager might remove and add inventories
# again. It caused pldmd fail to get inventories sometimes.
# Therefore, we temporary add bmc-ready check before we clarify the
# and fix entity-manager unexpected behavior.
bmc_ready=$(busctl get-property xyz.openbmc_project.State.BMC /xyz/openbmc_project/state/bmc0 xyz.openbmc_project.State.BMC CurrentBMCState | awk '{print $2}' | tr -d '"')
if [ "$bmc_ready" != "xyz.openbmc_project.State.BMC.BMCState.Ready" ]; then
    echo "BMC is not ready, exiting..."
    exit 0
fi

sleep 2
bus=$(($1 + 15))
echo "Start rescan slot $1 fru bus $bus."
# rescan eeprom for fru information
busctl call xyz.openbmc_project.FruDevice /xyz/openbmc_project/FruDevice xyz.openbmc_project.FruDeviceManager ReScanBus q $bus --timeout=120
echo "End rescan slot $1 fru bus $bus for fru removal."
# wait for fru device to be ready
sleep 10
# check if Wailua Falls is present
wailua_falls_present=$(busctl tree xyz.openbmc_project.FruDevice | grep Wailua_Falls)
# set 48V/12V HSC OCP values
if [ -n "$wailua_falls_present" ]; then
    set_gpio P48V_OCP_GPIO1       0
    set_gpio P48V_OCP_GPIO2       0
    set_gpio P48V_OCP_GPIO3       0
    set_gpio HSC_OCP_SLOT_ODD_GPIO1        1
    set_gpio HSC_OCP_SLOT_ODD_GPIO2        0
    set_gpio HSC_OCP_SLOT_ODD_GPIO3        0
    set_gpio HSC_OCP_SLOT_EVEN_GPIO1       1
    set_gpio HSC_OCP_SLOT_EVEN_GPIO2       0
    set_gpio HSC_OCP_SLOT_EVEN_GPIO3       0
else
    set_gpio P48V_OCP_GPIO1       1
    set_gpio P48V_OCP_GPIO2       0
    set_gpio P48V_OCP_GPIO3       0
    set_gpio HSC_OCP_SLOT_ODD_GPIO1        0
    set_gpio HSC_OCP_SLOT_ODD_GPIO2        1
    set_gpio HSC_OCP_SLOT_ODD_GPIO3        0
    set_gpio HSC_OCP_SLOT_EVEN_GPIO1       0
    set_gpio HSC_OCP_SLOT_EVEN_GPIO2       1
    set_gpio HSC_OCP_SLOT_EVEN_GPIO3       0
fi
echo "End slot $1 rescan-fru-oct-setting"
